/**
 * 
 */
package com.starhub.sample.webapp.controllers.personal.mobile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.starhub.sample.entities.Banner;
import com.starhub.sample.entities.Tab;
import com.starhub.sample.services.BannerService;
import com.starhub.sample.services.TabService;
import com.starhub.sample.webapp.dtos.AdminPersonalMobileForm;

/**
 * @author Hoan.NguyenTrong Jan 8, 2015
 * 
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    private static final int NUM_OF_BANNERS = 4;
    private static final int NUM_OF_TABS = 2;
    private static final int NUM_OF_TILES_PER_TAB = 4;
    private static final Log LOG = LogFactory.getLog(AdminController.class);

    @Autowired
    private ServletContext context;
    @Autowired
    private HttpSession session;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private TabService tabService;

    /**
     * To Load the Admin Personal Mobile page
     * 
     * @return
     */
    @RequestMapping(value = "/personal/mobile")
    public ModelAndView loadPersonalMobileAdminPage() {

	return loadAdminPersonalMobileParams();
    }

    /**
     * To handle the submission the admin personal mobile page
     * 
     * @param adminPersonalMobileForm
     * @return
     */
    @RequestMapping(value = "/personal/mobile/submit", method = RequestMethod.POST)
    public ModelAndView submitConfigurationOfPersonalMobilePage(
	    @ModelAttribute(value = "adminPersonalMobileForm") AdminPersonalMobileForm adminPersonalMobileForm) {

	// Process updating the Banner section
	updateBannerSection(adminPersonalMobileForm);

	// Process updating the section tiles
	updateSectionTiles(adminPersonalMobileForm);

	return new ModelAndView("redirect:/admin/personal/mobile");
    }

    /**
     * To Update all information of the Section Tiles
     * 
     * @param adminPersonalMobileForm
     */
    private void updateSectionTiles(AdminPersonalMobileForm form) {
	
	for (int tabIndex = 0; tabIndex < NUM_OF_TABS; tabIndex++) {
	    
	    Tab tab = form.getTabList().get(tabIndex);
	    
	    for(int tileIndex = 0; tileIndex < NUM_OF_TILES_PER_TAB; tileIndex++){
		int tileImageIndex = tabIndex * NUM_OF_TILES_PER_TAB + tileIndex;
		String uploadFilePath = saveImage(form.getTileImageList().get(tileImageIndex));
		if (uploadFilePath != null) {
			tab.getTabTiles().get(tileIndex).setImageLink(uploadFilePath);
		    }		
		tab.getTabTiles().get(tileIndex).setTab(tab);
	    }
	    
	    tabService.saveOrUpdate(tab);
	}
    }

    /**
     * To update all information of the Banner Section
     * 
     * @param adminPersonalMobileForm
     */
    private void updateBannerSection(AdminPersonalMobileForm form) {

	for (int i = 0; i < NUM_OF_BANNERS; i++) {

	    // Save banner background image
	    String uploadFilePath = saveImage(form.getBannerBgImageList().get(i));
	    if (uploadFilePath != null) {
		form.getBannerList().get(i).setBgImageLink(uploadFilePath);
	    }

	    // Update banner
	    bannerService.saveOrUpdate(form.getBannerList().get(i));
	}
    }

    /**
     * @param form
     * @param i
     * @return uploaded file path on server
     */
    private String saveImage(MultipartFile file) {
	if (file != null && file.getSize() > 0) {
	    UUID name = UUID.randomUUID();
	    try {
		byte[] bytes = file.getBytes();

		/* Creating the directory to store file */
		String rootPath = System.getProperty("catalina.home");
		File dir = new File(rootPath + File.separator + "tmpFiles");
		if (!dir.exists())
		    dir.mkdirs();

		// Create the file on server
		String fileName = String.valueOf(name) + file.getOriginalFilename();
		File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
		BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
		stream.write(bytes);
		stream.close();
		LOG.info("File Location=" + serverFile.getAbsolutePath());
		return "/resources/images/banners/" + fileName;
	    } catch (Exception e) {
		LOG.error("Failed to upload " + String.valueOf(name) + " => " + e.getMessage());
	    }
	}
	return null;
    }

    /**
     * To load parameters and put them into modelAndView object
     * 
     * @return
     */
    public ModelAndView loadAdminPersonalMobileParams() {

	ModelAndView mav = new ModelAndView("admin.personal.mobile.page");
	List<Banner> bannerList = bannerService.getAllBanners();
	List<Tab> tabList = tabService.getAllTabs();
	mav.addObject("bannerList", bannerList);
	mav.addObject("tabList", tabList);
	return mav;
    }
}
